<template>
  <el-dialog title="录入销项发票明细" :visible.sync="dialogVisible" width="1600px" :close-on-click-modal="false"
    :modal-append-to-body="false" v-drag2anywhere>
    <el-form :model="formData" ref="formData" label-width="100px" :rules="rules">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="发票号码" prop="num">
            <el-input v-model="formData.num" placeholder="发票号码" clearable @change="handleNumChange">
              <el-button slot="append" icon="el-icon-search" @click="handleQueryTicket">查询</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <div :span="18" style="line-height:30px; margin-left: 50px;">输入发票号码后，查询显示发票基本信息</div>
        <el-col >
          <div class="title">基本信息</div>
          <div style="line-height:30px; " v-if="ticketinfo">
              <span style="margin-right: 50px;">开票日期: <span style="color: #00aaff;">{{ticketinfo.date}}</span></span>
              <span style="margin-right: 50px;">购方名称: <span style="color: #00aaff;">{{ticketinfo.buyer}}</span></span>
              <span style="margin-right: 50px;">发票类型: <span style="color: #00aaff;">{{ticketinfo.type==1?'普通发票':(ticketinfo.type==2?"普通发票":(ticketinfo.type==3? "专用发票":"专用发票"))}}</span></span>
              <span style="margin-right: 50px;">非税金额: <span style="color: #00aaff;">{{ticketinfo.total}}</span></span>
              <span style="margin-right: 50px;">税额:<span style="color: #00aaff;">{{ticketinfo.tax}}</span></span>
               <span style="margin-right: 50px;">开票总额:<span style="color: #00aaff;">{{ticketinfo.sum}}</span></span>
              <span style="margin-right: 50px;">附件:<span style="color:#00aaff">
                  <el-button type="text" style="color: #00aaff;" v-if="ticketinfo.attach.length>0" @click="handlePreiview">查看附件</el-button>
                  </span>
              </span>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col>
          <div class="title">发票明细</div>
          <el-form-item label="" label-width="0">
            <div style="display: flex;">
              <div style="flex: 1;">标 <span style="color:#FF0000">*</span> 字段为必填项</div>
              <div>
                <el-button-group>
                  <el-button type="primary" :disabled="!ticketinfo" icon="el-icon-plus" size="mini" @click="handleAdd">新增明细</el-button>
                  <el-button type="primary" :disabled="!ticketinfo" icon="el-icon-finished" size="mini" @click="handleBuyTicketFilter">选择进项</el-button>
                  <el-button type="success" :disabled="!ticketinfo" icon="el-icon-upload2" size="mini" @click="handleImport">导入记录</el-button>
                </el-button-group>
              </div>
            </div>
            <div class="tablewraper">
              <el-table :data="formData.goods" border style="width: 100%;" height="100%" @select="handleSelection" @select-all="handleSelection">
                <el-table-column type="selection" width="50px" align="center"></el-table-column>
                <el-table-column label="序号" type="index" align="center" width="50px"></el-table-column>
                <el-table-column label="稅收类目" width="180px">
                  <template v-slot="scope">
                    <el-select filterable v-model="scope.row.taxname" clearable
                      @change="handleTaxClassifyChanged(scope.$index,scope.row)">
                      <el-option v-for="(item,index) in taxclassify" :key="index" :label="item.name" :value="item.name">
                        <div style="width: 500px;display: flex;" :title="item.keyword">
                          <div style="flex: 1;">{{item.name}}</div>
                          <span style="color:#d1d1d1;font-size: 12px;"> {{item.keyword}}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="货物或应税劳务、服务名称" >
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 货物或应税劳务、服务名称
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.title" type="textarea" :rows="1" placeholder="货物名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="规格型号" width="120px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.model" type="textarea" :rows="1" placeholder="型号"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" width="90px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.unit" placeholder="单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="95px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 数量
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.count" @change="handleCountChange(scope.$index,scope.row)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="center" width="120px">
                  <template v-slot="scope">
                    {{scope.row.price}}
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="total" width="130px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 金额
                  </template>
                  <template v-slot="scope">
                    {{scope.row.total.toFixed(2)}}
                  </template>
                </el-table-column>
                <el-table-column label="税率" prop="rate" width="100px" align="center">
                  <template v-slot="scope">
                    <el-select v-model="scope.row.rate" placeholder="请选择税率"
                      @change="handleRateChange(scope.$index,scope.row)">
                      <el-option label="免税" value="0"></el-option>
                      <el-option label="1%" value="0.01"></el-option>
                      <el-option label="1.5%" value="0.15"></el-option>
                      <el-option label="3%" value="0.03"></el-option>
                      <el-option label="5%" value="0.05"></el-option>
                      <el-option label="6%" value="0.06"></el-option>
                      <el-option label="9%" value="0.09"></el-option>
                      <el-option label="12%" value="0.12"></el-option>
                      <el-option label="13%" value="0.13"></el-option>
                      <el-option label="16%" value="0.16"></el-option>
                      <el-option label="17%" value="0.17"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="税额" align="center" prop="tax" width="120px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 税额
                  </template>
                  <template v-slot="scope">
                    {{scope.row.tax.toFixed(2)}}
                  </template>
                </el-table-column>
                <el-table-column label="金额(含税)" align="center" prop="total" width="150px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 金额(含税)
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.sum"  @change="handleSumChange(scope.$index,scope.row)" ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="60px">
                  <template v-slot="scope">
                    <el-button circle icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index,scope.row)">
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div>
              <div style="float: right; margin:5px;">
                <span style="margin-right:20px">记录总数: {{formData.goods.length}}</span>
                <span style="margin-right: 20px;">选中总额: {{sum_selection.toFixed(2)}}</span>
                <span style="margin-right:20px">非税总额: {{formData.total}}</span>
                <span style="margin-right:20px">税额: {{formData.tax}}</span>
                <span style="margin-right:20px">开票总额: {{formData.sum}}</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <BuyDetailFilterUI v-if="buyFilterVisible" ref="buyFilterUI" @completeHandler="handleFilterSelect"></BuyDetailFilterUI>
     <AttachViewerUI ref="attachUI" v-if="attachVisible" />

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">提交申请</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import BuyDetailFilterUI from './buyticketfilter.vue';
  import AttachViewerUI from '@/components/attachviewer.vue'
  export default {
    components: {
      AttachViewerUI,
      BuyDetailFilterUI
    },
    data() {
      return {
        checkAttach(rule, value, callback) {
          if (this.upconfig.fileList.length != 0) {
            return callback("请选择发票上传");
          } else {
            return true;
          }
        },
        taxclassify: [],
        formData: {
          total:0,
          sum:0,
          tax:0,
          num:'',
          goods: []
        },
        sum_selection:0,
        attachVisible:false,
        ticketinfo:null,
        buylist: [],
        clients: [],
        dialogVisible: false,
        buyFilterVisible: false,

        rules: {
          buyer: [{
            required: true,
            message: '请正确填写购买方名称!',
            trigger: 'blur'
          }],
          date: [{
            required: true,
            message: '请正确填写开票时间!',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请选择发票类型!',
            trigger: 'change'
          }],
          num: [{
            required: true,
            message: '请正确填写发票号码!',
            trigger: 'blur'
          }]
        },
      }
    },
    methods: {
      handleImport(){

      },
      handleSelection(list){
        this.sum_selection=0;
        list.forEach(item=>{
          this.sum_selection+=parseFloat(item.sum);
        })
      },
      handlePreiview(){
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.init(JSON.parse(JSON.stringify(this.ticketinfo.attach)));
        })
      },
      handleNumChange(){
        if(this.formData.num==""){
          this.ticketinfo=null;
          this.formData.goods=[];
        }
      },
      handleQueryTicket(ticketid){
        if(this.formData.num==''){
          return;
        }
        this.axios.post("api/admin/saleticket/find",{num:this.formData.num}).then(res => {
          if (res.status == 200 && res.data.code == 1) {
            this.ticketinfo=res.data.ticket;
            this.formData.goods=res.data.goods;
            this.handleRefreshBottomSum();
          }else{
            this.ticketinfo=null;
            this.formData.goods=[];
            this.$message.warning({message:'暂时查询到此发票信息!'});
            this.handleRefreshBottomSum();
          }
        });
      },
      handleBuyTicketFilter() {
        this.buyFilterVisible = true;
        this.$nextTick(() => {
          this.$refs.buyFilterUI.dialogVisible = true;
          this.$refs.buyFilterUI.initData();
        })
      },
      checkArrayObjectValueRepeat(dataArr, key, value) {
        let valArr = [],
          check = '';
        dataArr.some(item => {
          if (valArr.includes(item[key])) return check = '不能重复';
          valArr.push(item[key]);
          return false;
        })
        return check;
      },
      handleFilterSelect(goods) {
        for (var i = 0; i < goods.length; i++) {
          var result = this.formData.goods.some(item => item.did === goods[i].id);
          if (!result) {
            let ngoods=
              {
                id: -1,
                title: goods[i].title,
                model: goods[i].model,
                unit: goods[i].unit,
                count: goods[i].count,
                price: 0,
                total: 0,
                taxcode:goods[i].taxcode,
                taxname:goods[i].taxname,
                rate: goods[i].rate,
                sum: 0,
                tax: 0,
                reqid:this.ticketinfo.id,
                code:this.ticketinfo.code,
                date:this.ticketinfo.date,
                num: this.ticketinfo.num
            }
            this.formData.goods.push(ngoods);
          }
        }
        this.handleRefreshBottomSum();
      },
      handleSumChange(index,data){
         this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate))/parseFloat(this.formData.goods[index].count),8);
         this.formData.goods[index].total = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate)),8);
         this.formData.goods[index].tax=this.format2Number(this.formData.goods[index].total*parseFloat(this.formData.goods[index].rate),2);
         this.handleRefreshBottomSum();
      },
      handleCountChange(index, data) {
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate))/parseFloat(this.formData.goods[index].count),8);
        this.formData.goods[index].total = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate)),8);
        this.formData.goods[index].tax=this.format2Number(this.formData.goods[index].total*parseFloat(this.formData.goods[index].rate),2);
        this.handleRefreshBottomSum();
      },
      handleRateChange(index, row) {
        this.formData.goods[index].price = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate))/parseFloat(this.formData.goods[index].count),8);
        this.formData.goods[index].total = this.format2Number(this.formData.goods[index].sum / (1 + parseFloat(this.formData.goods[index].rate)),8);
        this.formData.goods[index].tax=this.format2Number(this.formData.goods[index].total*parseFloat(this.formData.goods[index].rate),2);
        this.handleRefreshBottomSum();
      },
      handleRefreshBottomSum() {
        this.formData.total = 0;
        this.formData.tax = 0;
        this.formData.sum=0;
        this.formData.goods.forEach(item => {
          item.total = this.format2Number(item.total, 2);
          this.formData.total += parseFloat(item.total);
          this.formData.tax += parseFloat(item.tax);
          this.formData.sum+=parseFloat(item.sum);
        })
        this.formData.tax = this.formData.tax.toFixed(2);
        this.formData.sum = this.formData.sum.toFixed(2);// (parseFloat(this.formData.total).toFixed(2) + parseFloat(this.formData.tax).toFixed(2));
      },
      handleTaxClassifyChanged(index, data) {
        var option = this.taxclassify.filter(function(cur, index, a) {
          if (cur.name == data.taxname) {
            return cur;
          }
        })[0];
        this.formData.goods[index].taxname = option.name;
        this.formData.goods[index].taxcode = option.code;
      },
      format2Number(value, len) {
        var f = parseFloat(value);
        return parseFloat(f.toFixed(parseInt(len)));
      },

      initData(num) {
        //重置参数
        this.formData = {
          num:'',
          sum:0,
          tax:0,
          total:0,
          goods: [],
         }
        this.ticketinfo=null;
        if (this.$refs.formData) {
          this.$refs.formData.resetFields();
        }
        this.loadClients();
        this.loadTaxClasasify();
        if(num!=''){
          this.handleQueryTicket(num);
        }
      },
      loadTaxClasasify() {
        this.axios.post("api/common/taxclassify/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.taxclassify = res.data.list;
          }
        });
      },
      loadClients() {
        this.axios.post("api/sup/supclient/list_opt").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.clients = res.data.list;
          }
        });
      },
      handleSave() {
        this.$refs.formData.validate(ok => {
          if (ok) {
            if (this.formData.goods.length <= 0) {
              this.$message.error({
                message: "采购明细不能为空!",
                duration: 1500,
                showClose: true
              });
              return;
            }
            //检测物品信息
            let index = 1;
            let verifyOk = true;
            for (var i = 0; i < this.formData.goods.length; i++) {
              index = (i + 1);
              if (this.formData.goods[i].taxcode == "") {
                this.$message.error({
                  message: '第' + index + "行 请选择相应的税收分类!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].title == "") {
                this.$message.error({
                  message: '第' + index + "行 货物或应税劳务、服务名称填写有误!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].count == "" || this.formData.goods[i].count == "") {
                this.$message.error({
                  message: '第' + index + "行 采购数量填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              }else if(parseFloat(this.formData.goods[i].sum)==0){
                this.$message.error({
                  message: '第' + index + "行 含税总额填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              }
            }

            if (!verifyOk) {
              return;
            }

            if (this.formData.sum == 0) {
              this.$message.error({
                message: "发票总额不能为0.00元",
                duration: 1500,
                showClose: true
              });
              return;
            }

            const params={
              reqid:this.ticketinfo.id,
              num:this.ticketinfo.num,
              code:this.ticketinfo.code,
              goods:JSON.stringify(this.formData.goods)
            }
            this.axios.post("api/admin/saleticketdetail/update",params).then(res=>{
              if (res.status == 200 && res.data.code) {
                this.$message.success({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
                this.dialogVisible = false;
                this.$emit("completeHandler");
              } else {
                this.$message.error({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
              }
            });

          }
        });
      },
      handleDelete(index, row) {
        this.$confirm("确定要删除此项吗?", "提示").then(() => {
          this.formData.goods.splice(index, 1);
        })
      },
      handleAdd() {
        this.formData.goods.push({
          id: -1,
          title: '',
          model: '',
          unit: '',
          count: 1,
          price: '0.000000000',
          total: 0,
          taxcode:'',
          taxname:'',
          rate: '0.13',
          sum: 0,
          tax: 0,
          num: this.ticketinfo.num,
          code:this.ticketinfo.code,
          date:this.ticketinfo.date
        });
      },
      handleClientChanged(clientname) {
        var option = this.clients.filter(function(cur, index, a) {
          if (cur.title == clientname) {
            return cur;
          }
        })[0];
      }
    }
  }
</script>

<style scoped>
  .tablewraper{
    height: 300px;
  }
</style>
